package tmts;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import models.Client;

public class BroadCastResponseListener implements Runnable
{

    private DatagramSocket datagramSocket;
    protected static final String RESPONSE_MESSAGE_START = "TMTS_CLIENT";

    public BroadCastResponseListener(DatagramSocket datagramSocket)
    {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run()
    {

        while (true)
        {
            //Wait for a response
            byte[] recvBuf = new byte[15000];
            DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
            try
            {
                datagramSocket.receive(receivePacket);
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            //We have a response
            System.out.println(getClass().getName() + ">>> Broadcast response from server: "
                    + receivePacket.getAddress().getHostAddress());

            //Check if the message is correct
            String message = new String(receivePacket.getData()).trim();
            if (message.startsWith(RESPONSE_MESSAGE_START))
            {
                int port = Integer.parseInt(message.substring(RESPONSE_MESSAGE_START.length()).trim());
                System.out.println("CLIENT FOUND AT " + receivePacket.getAddress().getHostAddress() + "  port" + port);
                Client client = new Client(receivePacket.getAddress().getHostAddress(), port);
                
                if (!ClientSendHandler.clientExists(client))
                {
                    ClientSendHandler.addClient(client);
                }
                else
                {
                    ClientSendHandler.sendAcceptMessage(client);
                }
            }
        }
    }
}
